<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\service\WechatService;
use think\facade\Log;

class Wechat extends BaseController
{
    protected $wechatService;
    
    public function __construct()
    {
        parent::__construct();
        $this->wechatService = new WechatService();
    }
    
    /**
     * 微信消息接收
     */
    public function receive()
    {
        $signature = input('signature');
        $timestamp = input('timestamp');
        $nonce = input('nonce');
        $echostr = input('echostr');
        
        // 验证签名
        if (!$this->wechatService->checkSignature($signature, $timestamp, $nonce)) {
            return 'Invalid signature';
        }
        
        // 如果是首次接入，返回echostr
        if ($echostr) {
            return $echostr;
        }
        
        // 接收消息
        $postData = file_get_contents('php://input');
        $message = $this->wechatService->receiveMessage($postData);
        
        if (!$message) {
            return 'success';
        }
        
        // 处理消息
        $this->handleMessage($message);
        
        return 'success';
    }
    
    /**
     * 处理消息
     */
    protected function handleMessage($message)
    {
        try {
            switch ($message['type']) {
                case 'text':
                    $this->handleTextMessage($message);
                    break;
                case 'image':
                    $this->handleImageMessage($message);
                    break;
                case 'voice':
                    $this->handleVoiceMessage($message);
                    break;
                case 'video':
                    $this->handleVideoMessage($message);
                    break;
                case 'link':
                    $this->handleLinkMessage($message);
                    break;
                case 'event':
                    $this->handleEventMessage($message);
                    break;
            }
        } catch (\Exception $e) {
            Log::error('Handle message error: ' . $e->getMessage());
        }
    }
    
    /**
     * 处理文本消息
     */
    protected function handleTextMessage($message)
    {
        // 这里可以根据业务需求处理文本消息
        // 例如：自动回复、关键词处理等
        $content = $message['content'];
        $fromUser = $message['from'];
        
        // 示例：简单的关键词回复
        if (strpos($content, '你好') !== false) {
            $this->wechatService->sendTextMessage($fromUser, '你好！很高兴为您服务！');
        }
    }
    
    /**
     * 处理图片消息
     */
    protected function handleImageMessage($message)
    {
        // 处理图片消息
        $fromUser = $message['from'];
        $mediaId = $message['mediaId'];
        $picUrl = $message['picUrl'];
        
        // 示例：回复收到图片
        $this->wechatService->sendTextMessage($fromUser, '收到您的图片了！');
    }
    
    /**
     * 处理语音消息
     */
    protected function handleVoiceMessage($message)
    {
        // 处理语音消息
        $fromUser = $message['from'];
        $mediaId = $message['mediaId'];
        $format = $message['format'];
        
        // 示例：回复收到语音
        $this->wechatService->sendTextMessage($fromUser, '收到您的语音消息了！');
    }
    
    /**
     * 处理视频消息
     */
    protected function handleVideoMessage($message)
    {
        // 处理视频消息
        $fromUser = $message['from'];
        $mediaId = $message['mediaId'];
        $thumbMediaId = $message['thumbMediaId'];
        
        // 示例：回复收到视频
        $this->wechatService->sendTextMessage($fromUser, '收到您的视频了！');
    }
    
    /**
     * 处理链接消息
     */
    protected function handleLinkMessage($message)
    {
        // 处理链接消息
        $fromUser = $message['from'];
        $title = $message['title'];
        $description = $message['description'];
        $url = $message['url'];
        
        // 示例：回复收到链接
        $this->wechatService->sendTextMessage($fromUser, '收到您的链接了！');
    }
    
    /**
     * 处理事件消息
     */
    protected function handleEventMessage($message)
    {
        $event = $message['event'];
        $fromUser = $message['from'];
        
        switch ($event) {
            case 'subscribe':
                // 处理关注事件
                $this->wechatService->sendTextMessage($fromUser, '感谢您的关注！');
                break;
            case 'unsubscribe':
                // 处理取消关注事件
                break;
            case 'click':
                // 处理点击事件
                $eventKey = $message['eventKey'];
                $this->handleClickEvent($fromUser, $eventKey);
                break;
        }
    }
    
    /**
     * 处理点击事件
     */
    protected function handleClickEvent($fromUser, $eventKey)
    {
        // 根据事件key处理不同的点击事件
        switch ($eventKey) {
            case 'MENU_ABOUT':
                $this->wechatService->sendTextMessage($fromUser, '这是关于我们的介绍...');
                break;
            case 'MENU_CONTACT':
                $this->wechatService->sendTextMessage($fromUser, '联系方式：xxx');
                break;
            default:
                $this->wechatService->sendTextMessage($fromUser, '收到您的点击事件了！');
        }
    }
    
    /**
     * 发送模板消息
     */
    public function sendTemplate()
    {
        $toUser = input('to_user');
        $templateId = input('template_id');
        $data = input('data/a');
        $url = input('url', '');
        $miniprogram = input('miniprogram/a', []);
        
        if (!$toUser || !$templateId || empty($data)) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $result = $this->wechatService->sendTemplateMessage($toUser, $templateId, $data, $url, $miniprogram);
        
        if ($result) {
            return json(['code' => 0, 'msg' => '发送成功']);
        } else {
            return json(['code' => 1, 'msg' => '发送失败']);
        }
    }
} 